<template>
    <div class="line_icon" @click="handleClick">
        <n-icon :size="18" color="#fff">
            <Bug />
        </n-icon>
        <div>v{{ version }}</div>
    </div>
    <n-modal v-model:show="showModal" :close-on-esc="false" :mask-closable="false">
        <n-card style="width: 400px" title="软件更新中" :bordered="false" size="huge" role="dialog" aria-modal="true">
            <div class="updataer__warning--text">
                <n-icon size="16" color="#FFA500">
                    <WarningOutline></WarningOutline>
                </n-icon>
                <p>软件更新中，请勿退出！</p>
            </div>
            <n-progress :color="{ stops: ['#E3F2FD', '#2080f0'] }" type="line" :percentage="processingComputed"
                indicator-placement="inside" processing />
        </n-card>
    </n-modal>
</template>

<script setup lang='ts' name="Updater">
import { check } from '@tauri-apps/plugin-updater';
import { relaunch } from '@tauri-apps/plugin-process';
import { Bug } from '@vicons/ionicons5'
import { useAppStore } from '@/stores/app';
import { invoke } from '@tauri-apps/api/core';
import { storeToRefs } from 'pinia';
import { useMessage } from 'naive-ui';

const loading = ref(false);
const appStore = useAppStore();
const showModal = ref(false);
const donwloadNumber = ref(0);
const totalLoadNumber = ref(0);
const message = useMessage();
const processingComputed = computed(() => {
    if (totalLoadNumber.value === 0) return 0;
    return Math.floor(donwloadNumber.value * 100 / totalLoadNumber.value);
})
// 更新
const handleClick = async () => {
    try {
        if (loading.value) return;
        loading.value = true;

        // 检查更新
        const update = await check();
        if (!update) throw new Error('update为null');
        showModal.value = true;
        let downloaded = 0;
        let contentLength = 0;

        // 检查update对象是否包含必要字段
        if (!update.version || !update.date || !update.body) throw new Error('更新信息不完整！');

        // 下载并安装更新
        await update.downloadAndInstall((event) => {
            switch (event.event) {
                case 'Started':
                    contentLength = event.data.contentLength || 0;
                    totalLoadNumber.value = contentLength;
                    break;
                case 'Progress':
                    downloaded += event.data.chunkLength;
                    donwloadNumber.value = downloaded;
                    break;
                case 'Finished':
                    break;
            }
        });
        message.success('更新完成，即将重启应用！');
        await relaunch();
    } catch (error: any) {
        showModal.value = false;
        if (error === 'Could not fetch a valid release JSON from the remote' || error.includes('已经是最新版本')) {
            message.warning(`v${appStore.version}已经是最新版本`);
        } else {
            message.error(`更新出错：${error?.message || error || '未知错误'}`);
        }
    } finally {
        loading.value = false;
    }
}
const { version } = storeToRefs(appStore);
const getVersionInfo = async () => {
    try {
        const version = await invoke('get_app_version') as string;
        appStore.setVersion(version);
    } catch (error) {
        appStore.setVersion('unknown');
    }
}
getVersionInfo();
</script>
<style scoped lang='scss'>
@use "sass:color";

.line_icon {
    height: 100%;
    padding: 0 1em;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 0.5em;
    color: #fff;
    font-size: 0.9em;

    &:hover {
        @include useTheme {
            background: color.adjust(getVar('titleBarBg'), $lightness: 15%);
        }
    }
}
</style>